package com.lin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.lin.entity.*;
import com.lin.mapper.UcenterMemberMapper;
import com.lin.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import darabonba.core.client.ClientOverrideConfiguration;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author 霖霖
 * @since 2023-03-23
 */
@Service
public class UcenterMemberServiceImp extends ServiceImpl<UcenterMemberMapper, UcenterMember> implements UcenterMemberService {
    @Autowired
    private AclUserRoleService aclUserRoleService;
    @Autowired
    private AclRoleService aclRoleService;

    @Autowired
    private AclPermissionService aclPermissionService;

    @Autowired
    private AclRolePermissionService aclRolePermissionService;

    @Override
    public boolean sendSms(String phone, Map<String, Object> map) throws ExecutionException, InterruptedException {
        if (StringUtils.isBlank(phone))
            return false;
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
//                .accessKeyId(ConstantPropertiesUtils.ACCESS_KEY_ID)
//                .accessKeySecret(ConstantPropertiesUtils.ACCESS_KEY_SECRET)
                .accessKeyId("LTAI5t5kyGiCdVq6i7ry7fP5")
                .accessKeySecret("AeinVQPHEwkgjKa6kccka0MtQTZx77")
                //.securityToken("<your-token>") // use STS token
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-shenzhen") // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();

        // Parameter settings for API request
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName("阿里云短信测试")
                .templateCode("SMS_154950909")
                .phoneNumbers(phone)
                .templateParam(JSONObject.toJSONString(map))
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // Synchronously get the return value of the API request
        SendSmsResponse resp = response.get();
        System.out.println(new Gson().toJson(resp));
        // Asynchronous processing of return values
        /*response.thenAccept(resp -> {
            System.out.println(new Gson().toJson(resp));
        }).exceptionally(throwable -> { // Handling exceptions
            System.out.println(throwable.getMessage());
            return null;
        });*/

        // Finally, close the client
        client.close();
        System.out.println("resp.getBody().getCode() = " + resp.getBody().getCode());
        return response.isDone();
    }

    @Override
    public List<AclRole> getRoles(String userId) {
        QueryWrapper<AclUserRole> aclUserRoleQueryWrapper = new QueryWrapper<>();
        aclUserRoleQueryWrapper.eq("user_id", userId);
        aclUserRoleQueryWrapper.select("role_id");
        List<AclUserRole> list = aclUserRoleService.list(aclUserRoleQueryWrapper);
        QueryWrapper<AclRole> aclRoleQueryWrapper = new QueryWrapper<>();
        aclRoleQueryWrapper.select("role_value", "id");
        aclRoleQueryWrapper.in("id", list.stream().map(AclUserRole::getRoleId).collect(Collectors.toList()));
        return aclRoleService.list(aclRoleQueryWrapper);
    }

    @Override
    public List<AclPermission> getPermissions(List<String> roleIds) {
        QueryWrapper<AclRolePermission> aclRolePermissionQueryWrapper = new QueryWrapper<>();
        aclRolePermissionQueryWrapper.in("role_id", roleIds);
        aclRolePermissionQueryWrapper.select("id");
        List<AclRolePermission> aclRolePermissionIds = aclRolePermissionService.list(aclRolePermissionQueryWrapper);
        List<String> permissionIds = aclRolePermissionIds.stream().map(AclRolePermission::getPermissionId).collect(Collectors.toList());

        return aclPermissionService.listByIds(permissionIds);
    }
    @Override
    @Transactional
    public boolean registerUser(UcenterMember user) {
        int num = baseMapper.insert(user);
        AclUserRole aclUserRole = new AclUserRole();
        aclUserRole.setUserId(user.getId());
        aclUserRole.setRoleId("2");
        return aclUserRoleService.save(aclUserRole) && num > 0;
    }

    @Override
    public Long statisticsCount(LocalDateTime yesterday) {
        return baseMapper.selectStatisticCount(yesterday);
    }
}
